#include "tcp.hpp"
#include<pthread.h>
#include<iostream>
using namespace MY_TCP;

void *link_http(void *argv)
{
    int fd = *(int *)argv;
    delete (int *)argv;

    char arr[1024];
    int size = recv(fd, arr, sizeof(arr), 0);
    if (size > 0)
    {
        std::cout << arr;

        std::string http_response = "http/1.0 200 OK\n";
        http_response += "Content-Type: text/plain\n";
        http_response += "\n";
        http_response += "./jsq.html\n";
        send(fd, http_response.c_str(), http_response.size(), 0);
    }

    close(fd);
    return nullptr;
}
void Usage(std::string command)
{
  std::cout << command << " port" << std::endl;
}   
int main(int args, char *argv[])
{
  if (args != 2)
  {
    std::cerr << "use error" << std::endl;
    Usage(argv[0]);
    exit(1);
  }
    int port = atoi(argv[1]);
    int sock_fd = TCP_SOCK::Sock();
    TCP_SOCK::Bind(sock_fd, port);
    TCP_SOCK::Listen(sock_fd, 5);
    while (true)
    {
        int new_fd = TCP_SOCK::Accept(sock_fd);
        pthread_t pid;
        int *fd = new int(new_fd);
        pthread_create(&pid, nullptr, link_http, (void *)fd);
    }
    return 0;
}